package com.tdd.mockexample;

import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;

public class LoginServiceTest {
	private Account account;
	private AccountRepoisitory repository;
	private LoginService loginService;

	@Before
	public void init() {
		account = mock(Account.class);
		repository = mock(AccountRepoisitory.class);
		when(repository.findAccountNamed(anyString())).thenReturn(account);
		loginService = new LoginService(repository);
	}

	private void passwordMatches(boolean state, Account account) {
		when(account.passwordMatches(anyString())).thenReturn(state);
	}

	@Test
	public void threeFailedAttemptsRevokesAccount() {
		passwordMatches(false, account);
		for(int i = 0; i < 3; ++i)
			loginService.login("account", "password");

		verify(account, times(1)).setRevoked(true);
	}

	@Test
	public void loginWithIncorrectPasswordDoesNotLoginAcocunt() {
		passwordMatches(false, account);

		loginService.login("account", "password");

		verify(account, never()).setLoggedIn(true);
	}

	@Test
	public void loginWithCorrectPasswordAndAccount() {
		passwordMatches(true, account);

		loginService.login("account", "password");

		verify(account, times(1)).setLoggedIn(true);
	}
}
